﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.UI;
using AbpDemo.Entity;
using study.Courses.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace study.Courses
{
    public class CourseAppService : studyAppServiceBase
    {
        private readonly IRepository<Course,long> _courseRepository;
        public CourseAppService(IRepository<Course,long> courseRepository)
        {
            _courseRepository = courseRepository;
        }

        /// <summary>
        /// 获取课程数据
        /// </summary>
        /// <returns></returns>
        public List<Course> OutPutAllCourse(CourseDto input)
        {
            var courseList = _courseRepository.GetAll();
            if (!string.IsNullOrEmpty(input.Keyword))
            {
                courseList = courseList.Where(s => (s.CourseCode.Contains(input.Keyword) || s.CourseName.Contains(input.Keyword)));
            }
            return courseList.ToList();
        }

        /// <summary>
        /// 更新课程
        /// </summary>
        /// <returns></returns>
        public void UpdateCourse(CourseDto input)
        {
            Course course = new Course() { Id = Convert.ToInt32(input.Id), CourseCode = input.CourseCode, CourseName = input.CourseName };
            _courseRepository.Update(course);
        }

        /// <summary>
        /// 删除课程
        /// </summary>
        /// <returns></returns>
        public void DelCourse(CourseDto input)
        {
            Course course = _courseRepository.Get(Convert.ToInt32(input.Id));
            _courseRepository.Delete(course);
        }

        /// <summary>
        /// 新增课程
        /// </summary>
        /// <returns></returns>
        public void CreateCourse(CreateCourseDto input)
        {
            var courseList = _courseRepository.GetAll().Where(c => c.CourseCode == input.CourseCode);
            if (courseList.Count() == 0)
            {
                var course = new Course() { CourseName = input.CourseName, CourseCode = input.CourseCode };
                _courseRepository.Insert(course);
            }
            else
                throw new UserFriendlyException("新增学生失败", "已有该学号，请重新输入");
        }
    }
}
